package top.juntower.controller;


import com.alibaba.druid.sql.visitor.functions.If;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.juntower.pojo.Feedback;
import top.juntower.pojo.User;
import top.juntower.pojo.dto.FootDta;
import top.juntower.pojo.dto.HistoryDto;
import top.juntower.service.impl.UserServiceImpl;
import top.juntower.utils.JsonResult;
import top.juntower.utils.Md5Salt;
import top.juntower.utils.QiniuUtil;
import top.juntower.utils.RedisUtils;

import java.io.FileInputStream;
import java.util.*;

@Api(tags = "用户信息")
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private RedisUtils redisUti;


    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    //登录判断
    @ApiOperation(value = "用户登录",response = User.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "usernum", value = "用户账号", dataType = "String", required = true),
            @ApiImplicitParam(name = "userpwd", value = "用户密码", dataType = "String", required = true),
    })
    @PostMapping("/loginuser")
    public JsonResult UserList(String usernum,String userpwd){
        if (usernum == null || userpwd == null){
            JsonResult.error(JsonResult.NO);
        }
        Map<String,String> map=new HashMap<>();
        map.put("userNum",usernum);
        map.put("userPwd",Md5Salt.md5PlusSalt(userpwd));
        User user = userService.queryUser(map);
        if (user==null){
            return JsonResult.error("用户不存在!");
        }
        return JsonResult.ok(user);
    }

    //判断是否被注册
    @ApiOperation(value = "判断是否被注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "用户邮箱", dataType = "String", required = true)
    })
    @GetMapping("/isSendEmail")
    public JsonResult isSendEmail(String email) {
        if (email == null) {
            JsonResult.error(JsonResult.NO);
        }
        //判断用户是否已存在
            int i = userService.queryEmail(email);
            if (i == 1) {
                return JsonResult.error("该邮箱已经被注册");
            }

        return JsonResult.ok("没有被注册");
    }

    //用户发送邮箱返回验证码
    @ApiOperation(value = "用户发送邮箱返回验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "用户邮箱", dataType = "String", required = true)
    })
    @GetMapping("/sendEmail")
    public JsonResult sendEmail(String email){
        if (email == null ){
            JsonResult.error(JsonResult.NO);
        }
        //判断用户是否已存在
            int i = userService.queryEmail(email);
            if (i == 1) {
                return JsonResult.error("该邮箱已经被注册");
            }
            String randomCode = randomCode();
            try {
                new Thread(() -> {
                    SimpleMailMessage message = new SimpleMailMessage();
                    //发件人的邮箱地址
                    message.setFrom(JsonResult.EMAIL);
                    //收件人的邮箱地址
                    message.setTo(email);
                    //邮件主题
                    message.setSubject("验证码");
                    //邮件内容
                    message.setText("尊敬的" + email + "用户,您好：\n你的验证码为 " + randomCode + "\n");
                    //发送邮件
                    javaMailSender.send(message);
                }).start();
            } catch (Exception e) {
                return JsonResult.error("发送失败");
            }
            redisUti.set(email,randomCode,2*60);
            return JsonResult.ok("发送成功");
    }

    //用户注册
    @ApiOperation(value = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", required = true),
            @ApiImplicitParam(name = "usernum", value = "用户账号", dataType = "String", required = true),
            @ApiImplicitParam(name = "userpwd", value = "用户密码", dataType = "String", required = true),
            @ApiImplicitParam(name = "email", value = "用户邮箱", dataType = "String", required = true),
            @ApiImplicitParam(name = "code", value = "用户验证码", dataType = "String", required = true)
    })
    @PostMapping("/register")
    public JsonResult register(String username,String usernum,String userpwd,String email,String code) {
        if (username == null || usernum == null || userpwd == null || email == null || code == null) {
            JsonResult.error(JsonResult.NO);
        }
        int i = userService.queryEmail(email);
        if (i == 1) {
                return JsonResult.error("该邮箱已经被注册");
            }
        if (redisUti.get(email) != null && redisUti.get(email).equals(code)) {
            Map<String, String> map = new HashMap<>();
            map.put("username", username);
            map.put("usernum", usernum);
            map.put("userpwd", Md5Salt.md5PlusSalt(userpwd));
            map.put("useremail", email);
            int register = userService.register(map);
            if (register > 0) {
                return JsonResult.ok("ok");
            }
            return JsonResult.error(JsonResult.INSERT_MISS);
        }else {
            return JsonResult.error("验证码或邮箱不正确");
        }
    }

    //查询用户信息
    @ApiOperation(value = "查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true)
    })
    @PostMapping("/queryUserInfo")
    public JsonResult queryUserInfo(Integer userId) {
        if (userId == null) {
            JsonResult.error(JsonResult.NO);
        }
        User user = userService.queryUserInfo(userId);
        if (user == null){
            JsonResult.error(JsonResult.NO);
        }
        return  JsonResult.ok(user);
    }

    //查看历史信息
    @ApiOperation(value = "查看历史信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true)
    })
    @GetMapping("/queryHistory")
    public JsonResult queryHistory(Integer userId) {
        if (userId == null) {
            JsonResult.error(JsonResult.NO);
        }
        List<HistoryDto> historyDtos = userService.queryHistory(userId);
        if (historyDtos == null){
            return  JsonResult.error(JsonResult.MISS);
        }
        return  JsonResult.ok(historyDtos);
    }

    //增加历史记录
    @ApiOperation(value = "增加历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "fId", value = "食物Id", dataType = "Integer", required = true)
    })
    @GetMapping("/updateHistory")
    public JsonResult updateHistory(Integer userId,Integer fId) {
        if (fId == null || userId == null) {
          return JsonResult.error(JsonResult.NO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("hDatetime",new Date());
        map.put("fId",fId);
        int i = userService.insertHistory(map);
        if (i>0){
            return JsonResult.ok("添加成功");
        }
        return  JsonResult.error("添加失败");
    }

    //删除历史记录
    @ApiOperation(value = "删除历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hId", value = "历史记录Id", dataType = "Integer", required = true),
    })
    @GetMapping("/deleteHistory")
    public JsonResult deleteHistory(Integer hId) {
        if (hId == null) {
            JsonResult.error(JsonResult.NO);
        }

        int i = userService.deleteHistory(hId);
        if (i>0){
            return JsonResult.ok("删除成功");
        }
        return  JsonResult.error("删除失败");
    }

    //删除用户全部历史记录
    @ApiOperation(value = "删除用户全部历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true),
    })
    @GetMapping("/deleteUserIdHistory")
    public JsonResult deleteUserIdHistory(Integer userId) {
        if (userId == null) {
            JsonResult.error(JsonResult.NO);
        }

        int i = userService.deleteUserIdHistory(userId);
        if (i>0){
            return JsonResult.ok("删除成功");
        }
        return  JsonResult.error("删除失败");
    }


    //修改用户头像
    @CrossOrigin
    @ApiOperation(value = "修改用户头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "用户头像图片", dataType = "MultipartFile", required = true),
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true)
    })
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam("file") MultipartFile file,Integer userId) {
        if (file.isEmpty()) {
            return JsonResult.error("请选择文件");
        }
        try {
            QiniuUtil qiniuUtil = new QiniuUtil();
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            //默认不指定key的状况下，以文件内容的hash值做为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + fileExtend;

            String tupain="http://juntower.top/"+fileKey;
            qiniuUtil.upload(fileInputStream,fileKey);
            //修改数据库图片
            Map<String, Object> map = new HashMap<>();
            map.put("userId",userId);
            map.put("userImg",tupain);
            userService.updateUserImg(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("上传失败");
        }
        return JsonResult.ok("上传成功");
    }

    //修改用户名称
    @ApiOperation(value = "修改用户名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "userName", value = "用户名称", dataType = "String", required = true)
    })
    @GetMapping("/updateUserName")
    public JsonResult updateUserName(Integer userId,String userName) {
        if (userId == null || userName == null) {
            JsonResult.error(JsonResult.NO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("userName",userName);
        int i = userService.updateUserName(map);
        if (i>0){
            return JsonResult.ok("修改成功");
        }else {
            return  JsonResult.error("修改失败");
        }
    }

    //批量删除历史记录
    @ApiOperation(value = "批量删除历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moreUserId", value = "历史记录Id", dataType = "String", required = true),
    })
    @PostMapping("/deleteMoreUserIdHistory")
    public JsonResult deleteHistory(String moreUserId) {
        if (moreUserId == null) {
            JsonResult.error(JsonResult.NO);
        }
        List<Integer> del_ids=new ArrayList<>();
        String[] str_ids=moreUserId.split(",");
        for (String str_id : str_ids) {
            del_ids.add(Integer.parseInt(str_id));
        }
        int i = userService.deleteMoreUserIdHistory(del_ids);
        System.out.println(i);
        if (i > 0){
            return  JsonResult.ok("删除成功");
        }else {
            return  JsonResult.error("删除失败");
        }
    }

    //查询所有用户信息后台
    @ApiOperation(value = "查询所有用户信息后台")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "分页页码", dataType = "Integer", required = true)
    })
    @PostMapping("/queryUserList")
    public JsonResult queryUserList(Integer pageNum) {
        if (pageNum == null){
            return  JsonResult.error(JsonResult.NO);
        }
        //使用分页插件,核心代码就这一行
        PageHelper.startPage(pageNum,6);
        List<User> users = userService.queryUserList(pageNum,6);
        PageInfo<User> pageInfo = new PageInfo<User>(users);
        if (users == null){
            return  JsonResult.error(JsonResult.MISS);
        }else {
            return  JsonResult.ok(pageInfo);
        }
    }

    //用户信息模糊查询后台
    @ApiOperation(value = "用户信息模糊查询后台")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "likeKeywords", value = "模糊查询关键字", dataType = "String", required = true),
            @ApiImplicitParam(name = "pageNum", value = "分页页码", dataType = "Integer", required = true)
    })
    @PostMapping("/queryLikeUserList")
    public JsonResult queryLikeUserList(String likeKeywords,Integer pageNum) {
        if (likeKeywords == null || pageNum == null){
            return  JsonResult.error(JsonResult.NO);
        }
        PageHelper.startPage(pageNum,6);
        List<User> users = userService.queryLikeUserList(likeKeywords,pageNum,6);
        PageInfo<User> pageInfo = new PageInfo<User>(users);
        if (users == null) {
            return  JsonResult.error(JsonResult.MISS);
        }else {
            return  JsonResult.ok(pageInfo);
        }
    }

    //增加用户反馈信息
    @ApiOperation(value = "增加用户反馈信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "fbContent", value = "意见类型", dataType = "String", required = true)
    })
    @PostMapping("/addFeedback")
    public JsonResult addFeedback(Integer userId,String fbContent) {
        if (userId == null || fbContent == null){
            return  JsonResult.error(JsonResult.NO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("fbContent",fbContent);
        int i = userService.addFeedback(map);
        if (i>0){
           return JsonResult.ok(JsonResult.INSERT_SUCCESS);
        }else {
            return JsonResult.error(JsonResult.INSERT_MISS);
        }
    }

    //查看用户反馈信息后台
    @ApiOperation(value = "查看用户反馈信息后台")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "分页页码", dataType = "Integer", required = true)
    })
    @PostMapping("/queryFeedback")
    public JsonResult queryFeedback(Integer pageNum) {
        if (pageNum == null){
            return  JsonResult.error(JsonResult.NO);
        }
        PageHelper.startPage(pageNum,8);
        List<Feedback> feedbacks = userService.queryFeedback(pageNum, 8);
        PageInfo<Feedback> pageInfo = new PageInfo<Feedback>(feedbacks);
        if(feedbacks == null){
            return JsonResult.error(JsonResult.MISS);
        }else {
            return  JsonResult.ok(pageInfo);
        }
    }

    //修改用户状态后台
    @ApiOperation(value = "修改用户状态后台")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "userState", value = "用户状态（1 存在 0 不存在）", dataType = "Integer", required = true)
    })
    @PostMapping("/deleteUser")
    public JsonResult deleteUser(Integer userId,Integer userState) {
        if (userId == null){
            return  JsonResult.error(JsonResult.NO);
        }
        int i = userService.deleteUser(userId,userState);
        if (i>0){
            return  JsonResult.ok(JsonResult.UPDATE_SUCCESS);
        }else {
            return JsonResult.error(JsonResult.UPDATE_MISS);
        }
    }

    //发送验证码
    @ApiOperation(value = "发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userEmail", value = "用户邮箱", dataType = "String", required = true),
    })
    @PostMapping("/sendEmailTo")
    public JsonResult sendEmailTo(String userEmail) {
        if (userEmail == null){
            return  JsonResult.error(JsonResult.NO);
        }
        int i = userService.queryEmail(userEmail);
        System.out.println(i);
        if (i == 1) {
            String randomCode = randomCode();
            try {
                new Thread(() -> {
                    SimpleMailMessage message = new SimpleMailMessage();
                    //发件人的邮箱地址
                    message.setFrom(JsonResult.EMAIL);
                    //收件人的邮箱地址
                    message.setTo(userEmail);
                    //邮件主题
                    message.setSubject("验证码");
                    //邮件内容
                    message.setText("尊敬的" + userEmail + "用户,您好：\n你的验证码为 " + randomCode + "\n");
                    //发送邮件
                    javaMailSender.send(message);
                }).start();
            } catch (Exception e) {
                return JsonResult.error("发送失败");
            }
            redisUti.set(userEmail,randomCode,2*60);
            return JsonResult.ok("发送成功");
        }else {
            return  JsonResult.error("该邮箱未注册");
        }
    }

    //验证邮箱验证码是否正确
    @ApiOperation(value = "验证邮箱验证码是否正确")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userEmail", value = "用户邮箱", dataType = "String", required = true),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", required = true)
    })
    @PostMapping("/verificationCode")
    public JsonResult verificationCode(String userEmail,String code) {
        if (userEmail == null || code == null){
            return  JsonResult.error(JsonResult.NO);
        }
        if (redisUti.get(userEmail) != null && redisUti.get(userEmail).equals(code)) {
            return JsonResult.ok("验证码正确");
        }else {
            return JsonResult.error("验证码或邮箱不正确");
        }
    }

    //修改密码
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userEmail", value = "用户邮箱", dataType = "String", required = true),
            @ApiImplicitParam(name = "newPassWord", value = "新密码", dataType = "String", required = true)
    })
    @PostMapping("/updatePassword")
    public JsonResult updatePassword(String userEmail,String newPassWord) {
        if (userEmail == null || newPassWord == null){
            return  JsonResult.error(JsonResult.NO);
        }
        Map<String,String> map=new HashMap<>();
        map.put("userEmail",userEmail);
        map.put("newPassWord",Md5Salt.md5PlusSalt(newPassWord));
        int i = userService.updatePassword(map);
        if (i>0){
            return JsonResult.ok(JsonResult.UPDATE_SUCCESS);
        }else {
            return JsonResult.error(JsonResult.UPDATE_MISS);
        }
    }

}
